import on from '@feidao-factory/core/on';

const OFFSET = 20;
const FEIDAO_VISIBLE = 'data-feidao-visible';
const FD_FORCE_VISIBLE = 'data-feidao-force-visible';

/**
 * 判断节点是否在可视区
 * @param node 需要判断的节点
 */
function in_viewport(node: Element) {
	const body = window.document.documentElement!;
	const nbcr = node.getBoundingClientRect();
	return nbcr.bottom > 0 && nbcr.right > 0 && nbcr.left < body.clientWidth && nbcr.top < body.clientHeight + OFFSET;
}

/**
 * 延迟加载节点，并把事件句柄记录到节点中，方便销毁事件
 * @param node
 */
export default function lazyload(node: Element) {
	return new Promise<Element>((resolve) => {
		const visible = node[FEIDAO_VISIBLE] || node.getAttribute(FD_FORCE_VISIBLE);
		if (in_viewport(node) || (visible === true) || (visible === 'true')) {
			resolve(node);
			return;
		}
		const handle = on(window, ['scroll', 'resize'], () => {
			if (in_viewport(node)) {
				if (handle) {
					handle.destroy();
				}
				resolve(node);
			}
		});
	});
}
